<?php
/**
 * Created by jinqiang on 2024/7/1 17:41.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Controllers\Produce;


use App\Http\Controllers\Controller;
use App\Http\Services\Produce\ProcessingService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\Finder\Finder;

class ProcessingController extends Controller
{
    public function list(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'page' => 'required',
            'limit' => 'required'
        ]);
        $param = $request->all();
        $res = $processingService->search($param);
        return result($res);
    }

    //生成洗唛、吊牌唯一码
    public function rfidCreate(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'data' => 'required',
            'status' => 'required'
        ]);
        $param = $request->all();
        $res = $processingService->rfidCreate($param);
        return $res['code'] === 0 ? success("创建成功") : error($res['msg'], $res);
    }

    //启用、禁用
    public function open(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'processing_code' => 'required',
            'status' => 'required'
        ]);
        $param = $request->all();
        $res = $processingService->open($param);
        return $res['code'] === 0 ? success("操作成功") : error($res['msg'], $res);
    }

    //推送、取消
    public function push(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'processing_code' => 'required',
            'status' => 'required'
        ]);
        $param = $request->all();
        $processingCode = $param['processing_code'];
        $status = (Int)$param['status'];
        if($status == 1){
            $res = $processingService->push($processingCode);
        }else{
            $res = $processingService->cancel($processingCode);
        }
        return $res['code'] === 0 ? success("操作成功") : error($res['msg'], $res);
    }

    //强制完成
    public function end(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'processing_code' => 'required',
        ]);
        $param = $request->all();
        $res = $processingService->end($param['processing_code']);
        return $res['code'] === 0 ? success($res['msg']) : error($res['msg'], $res);
    }

    //设置批次
    public function batchSet(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'processing_code' => 'required',
            'batch_id' => 'required'
        ]);
        $param = $request->all();
        $res = $processingService->batchSet($param['processing_code'], $param['batch_id']);
        return $res['code'] === 0 ? success("操作成功") : error($res['msg'], $res);
    }

    public function skuList(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'processing_code' => 'required',
        ]);
        $param = $request->all();
        $res = $processingService->searchSku($param['processing_code']);
        return result($res);
    }

    //采退、返修
    public function goodReturn(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'data' => 'required',
            'type' => 'required'
        ]);
        $param = $request->all();
        $res = $processingService->goodReturn($param['data'], $param['type'], $param['remark']);
        return $res['code'] === 0 ? success("操作成功") : error($res['msg'], $res);
    }

    //报次修改
    public function baociSet(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'data' => 'required',
        ]);
        $param = $request->all();
        $res = $processingService->baociSet($param['data']);
        return $res['code'] === 0 ? success("操作成功") : error($res['msg'], $res);
    }

    //增裁
    public function zengcSet(Request $request, ProcessingService $processingService)
    {
        $this->validate($request, [
            'data' => 'required',
        ]);
        $param = $request->all();
        $res = $processingService->zengcSet($param['data']);
        return $res['code'] === 0 ? success("操作成功") : error($res['msg'], $res);
    }

    //获取导出文件列表
    public function excelList(Request $request)
    {
        $user = auth()->guard("api")->user();
        $name = $user->name;
        $nameId = $user->id;
        $processKey = "PROCESSING_EXCEL_EXPORT_{$nameId}";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        $finder = new Finder();
        $files = $finder->files()->in(storage_path("cache/processing"))->name("加工单_{$name}*.xls");
        $data = [];
        $createTimeList = [];
        foreach ($files as $file) {
            $fileName = $file->getFilename();
            $createUser = preg_match("/加工单_(.*?)_(\d{14})\.xls/is", $fileName, $d) ? $d[1] : "";
            $data[] = [
                'create_user' => $createUser,
                'create_time' => date('Y-m-d H:i:s', strtotime($d[2])),
                'name' => $fileName,
                'status' => ($cache['file']??"") == $fileName ? 0 : 1,
                'process' => ($cache['file']??"") == $fileName ? $cache['process'] : 100
            ];
            $createTimeList[] = strtotime($d[2]);
        }
        array_multisort($createTimeList, SORT_DESC, $data);
        return result(['data' => $data, 'cache' => $cache]);
    }

    //获取导出进度
    public function exportCache()
    {
        $user = auth()->guard("api")->user();
        $nameId = $user->id;
        $processKey = "PROCESSING_EXCEL_EXPORT_{$nameId}";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        return result($cache);
    }

    //导出执行
    public function exportData(Request $request)
    {
        $param = $request->all();
        $user = auth()->guard("api")->user();
        $name = $user->name;
        $nameId = $user->id;
        //添加导出的任务进度
        $processKey = "PROCESSING_EXCEL_EXPORT_{$nameId}";
        if(Cache::get($processKey)){
            return error("添加失败, 最近一次导出计划还未完成");
        }
        $cTime = date('YmdHis');
        $filename = "加工单_{$name}_{$cTime}.xls";
        $file = storage_path("cache/processing/").$filename;
        $spreadsheet = new Spreadsheet();
        $writer = new Xlsx($spreadsheet);
        $writer->save($file);
        if(file_exists($file)){
            $bandCodes = array_column(config("scm.subject"), 'brand_code_s', 'is_subject');
            $param['brand_code'] = $bandCodes[$user->is_subject];
            $cache = ['file' => $filename, 'process' => 0, 'param' => $param];
            Cache::put($processKey, $cache, Carbon::now()->addSeconds(60));
            $cmd = 'php '.base_path().'/artisan command:exportData --type=processing --id='.$nameId.' >/dev/null 2>&1 &';
            ppopen($cmd);
            return success("添加成功", $cache);
        }else{
            return error("添加失败, 创建文件失败");
        }
    }
}
